import json

from django.views import View
from django.views.generic import TemplateView
from django.views.decorators.cache import never_cache
from rest_framework import viewsets
from rest_framework.views import APIView

from .apps import AppConfig
from .models import Message, MessageSerializer, FishInfo, FishInfoSerializer
from .models import DlModel, DlModelSerializer
from django.views.decorators.csrf import csrf_exempt

from django.http import HttpResponse, JsonResponse
from rest_framework.renderers import JSONRenderer
from rest_framework.parsers import JSONParser

# Serve Vue Application
index_view = never_cache(TemplateView.as_view(template_name='index.html'))
from backend.api.control.dynamic_deploy import LazyImport

from rest_framework.decorators import api_view

# classer = None
deployed_model = {}


class MessageViewSet(viewsets.ModelViewSet):
    """
    API endpoint that allows messages to be viewed or edited.
    """
    queryset = Message.objects.all()
    serializer_class = MessageSerializer


class MyModels(viewsets.ModelViewSet):
    queryset = DlModel.objects.all().order_by('-pk')
    serializer_class = DlModelSerializer


class FishInfo(viewsets.ModelViewSet):
    queryset = FishInfo.objects.all().order_by('-pk')
    serializer_class = FishInfoSerializer


# @csrf_exempt
# class ClassifyFishes(View):
#     def post(self,request):
#         dict_data = json.loads(request.body.decode())  # 注意，需要引入json
#         image_data = dict_data.get('image_data')
#         result = AppConfig.classifier.predict(image_data)
#         return result


# @api_view(['GET', 'POST'])
@csrf_exempt
def call_model(request):
    # dict_data = json.loads(request.POST.decode())  # 注意，需要引入json
    image_data = request.POST.get('image_data', '')
    # siege can't transfer +, + will be replaced by space
    image_data = image_data.replace(" ", "+")
    # print(image_data)

    # importmodule = LazyImport("backend.api.classify." + "classifier", "classifier")  # 导入classname模块
    # is_true = hasattr(importmodule, "classifier")  # 检查classname类是否在classname模块中
    # if is_true:
    #     classname = getattr(importmodule, "classifier")
    #     # 传递参数
    #     global classer
    #     if (classer is None):
    #         classer = classname()
    #     # obj = classname()  # 实例化classname类
    #     mtd = getattr(classer, 'predict')
    #     result, score = mtd(image_data)  # 调用run方法，接收return返回值
    #     # print(dd)
    #     # result, score = AppConfig.classifier.predict(image_data)
    #     result['score'] = score
    add_model(None)
    global  deployed_model
    print(deployed_model)
    classer = deployed_model["backend.api.classify.classifier.classifier"]
    mtd = getattr(classer, 'predict')
    result, score = mtd(image_data)  # 调用run方法，接收return返回值
    # print(dd)
    # result, score = AppConfig.classifier.predict(image_data)
    result['score'] = score

    # return HttpResponse(result)
    return JsonResponse(data=result, safe=False)
    # return HttpResponse(json.dumps(result))

#
# @csrf_exempt
# def dlmodels(request):
#     """
#     List all code snippets, or create a new snippet.
#     """
#     if request.method == 'GET':
#         queryset = DlModel.objects.all()
#         serializer = DlModelSerializer(queryset, many=True)
#         return JsonResponse(serializer.data, safe=False)
#
#     elif request.method == 'POST':
#         data = JSONParser().parse(request)
#         serializer = DlModelSerializer(data=data)
#         if serializer.is_valid():
#             serializer.save()
#             return JsonResponse(serializer.data, status=200)
#     return JsonResponse(serializer.errors, status=400)
@csrf_exempt
def add_model(request):
    module_name="backend.api.classify"
    module_file="classifier"
    module_class="classifier"

    moudle_key = module_name+"."+module_file+"."+module_class

    importmodule = LazyImport(module_name+"."+ module_file, module_class)  # 导入classname模块
    is_true = hasattr(importmodule, module_class)  # 检查classname类是否在classname模块中
    if is_true:
        classname = getattr(importmodule, module_class)
        # 传递参数
        global deployed_model
        if (moudle_key not in deployed_model):
            classer = classname()
            deployed_model[moudle_key] =classer
        # obj = classname()  # 实例化classname类
        # classer = deployed_model[moudle_key]
        # mtd = getattr(classer, 'predict')
        # result, score = mtd(image_data)  # 调用run方法，接收return返回值
        # # print(dd)
        # # result, score = AppConfig.classifier.predict(image_data)
        # result['score'] = score

    # return HttpResponse(result)
    return JsonResponse(data=moudle_key, safe=False)
    # return HttpResponse(json.dumps(result))
